﻿using System.Data;
using WorkFlow.DBProxy;

namespace WorkFlow.Engine.NSActivity.NSRoutes
{
    /// <summary>
    ///     排他路由
    /// </summary>
    public class WfExclusivenessTypeRoute
    {
        /// <summary>
        /// 排他路由合并 但前面的有一条为真即可
        /// </summary>
        /// <param name="act"></param>
        public void XorJoin(WfActivity act, int activatorID)
        {
            ///获取前置活动列表
            DataTable dt =
                DB.MapToDataTable(
                    string.Format(
                        @"select f_id from t_activities t where  exists(
                                       select f_pre_activity from tr_paths p where t.f_r_act_id=p.f_pre_activity and f_after_activity =(
                                             select f_r_act_id from t_activities where f_id={0}
                                       )
                                ) and f_process_id={1} and F_STATUS= {2}",
                        act.ID, act.ProcessId, WfFieldCode.DbCompleteState));
            if (dt == null || dt.Rows.Count == 0)
            {
                act.Ready(activatorID);
                return;
            }
            //如果前面的条件有一个为真
            act.Run(); //如果在调用complete()前活动实例的状态不为runState,将不会执行complete()
            act.Complete();
        }

        /// <summary>
        /// 排他分支 后续活动随机选择一只激活
        /// </summary>
        /// <param name="act"></param>
        /// <param name="inputValue"></param>
        public void XorSplit(WfActivity act, int activatorID, int? inputValue)
        {
            int curActId = act.ID;
            int curProcId = act.ProcessId;
            //-----结束当前活动
            act.Run();
            act.Complete();

            //---------获取后续活动ID列表
            DataTable dt = DB.MapToDataTable(
                string.Format(
                    @"select f_id from t_activities t where  exists(
       select f_after_activity from tr_paths p where t.f_r_act_id=p.f_after_activity and f_pre_activity =(
             select f_r_act_id from t_activities where f_id={0}
       )
) and f_process_id={1}", curActId, curProcId));
            if (dt == null || dt.Rows.Count == 0) return;
            //随机选择一条激活
            WfActivityController.CreateActivityController().GetActivity(int.Parse(dt.Rows[0]["F_ID"].ToString()), WfFieldCode.DbNone);
        }
    }
}